from rest_framework import serializers
from .models import City, IDC, Host, HostStatistic

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = "__all__"

class IDCSerializer(serializers.ModelSerializer):
    class Meta:
        model = IDC
        fields = "__all__"

class HostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Host
        fields = ["id", "hostname", "ip", "idc", "created_at", "updated_at"]  # 隐藏密码
        read_only_fields = ["created_at", "updated_at"]

    def create(self, validated_data):
        # 创建主机时自动生成加密密码
        from .tasks import generate_random_password, encrypt_password
        encrypted_pwd = encrypt_password(generate_random_password())
        return Host.objects.create(**validated_data, root_password=encrypted_pwd)

class HostStatisticSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostStatistic
        fields = "__all__"